package com.hx.yupao.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hx.yupao.common.ErrorCode;
import com.hx.yupao.exception.BusinessException;
import com.hx.yupao.model.domain.User;
import com.hx.yupao.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hx.yupao.constant.RedisConstant.REDISSON_RECOMMEND_KEY;
import static com.hx.yupao.constant.RedisConstant.REDIS_RECOMMEND_KEY;

/**
 * 缓存预热任务
 */
@Component
@Slf4j
public class PreCacheJob {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private RedissonClient redissonClient;

    //重点用户
    private List<Long> mainUserList = Arrays.asList(1L);

    //每天执行，预热推荐用户
    @Scheduled(cron = "0 59 23 * * ?")
    public void doCacheRecommendUser() {
        RLock lock = redissonClient.getLock(REDISSON_RECOMMEND_KEY);
        try {
            if (lock.tryLock(0, -1, TimeUnit.MILLISECONDS)) {
                System.out.println("lock" + Thread.currentThread().getId());
                for (Long userId : mainUserList) {
                    String redisKey = String.format(REDIS_RECOMMEND_KEY, userId);
                    ValueOperations valueOperations = redisTemplate.opsForValue();
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    Page<User> userPage = userService.page(new Page<>(1, 8), queryWrapper);
                    //写缓存
                    try {
                        valueOperations.set(redisKey, userPage, 30000, TimeUnit.MILLISECONDS);
                    } catch (Exception e) {
                        log.error("redis set key error", e);
                    }
                }

            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //只能释放自己的锁，放在finally防止前面出错中断，执行不到释放锁的代码
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
                System.out.println("unlock" + Thread.currentThread().getId());
            }
        }
    }
}
